const fs = require('fs')
const COS = require('cos-nodejs-sdk-v5')
const cos = new COS({
  SecretId: 'AKIDUwVxKaikjbR9rUIHCPqKnJmGqTFC7EJJ',
  SecretKey: 'IgDxeXmCseNHGFRn6WQDvW0LnPG0YuW6'
})

class UploadService {
  // 上传文件到腾讯云oss的配置信息
  async uploadFile(file) {
    const result = await cos.putObject({
      Bucket: 'echo-1314434456',
      Region: 'ap-chengdu',
      Key: file.filename, // 文件名
      Body: fs.createReadStream(file.filepath) // 文件路径
    })
    return result
  }
  // 上传文件
  async upload(file) {
    return new Promise((resolve, reject) => {
      this.uploadFile(file)
        .then((res) => {
          resolve(res)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }
  // 删除文件
  async deleteFile(key) {
    return new Promise((resolve, reject) => {
      cos.deleteObject(
        {
          Bucket: 'echo-1314434456',
          Region: 'ap-chengdu',
          Key: key
        },
        (err, data) => {
          if (err) {
            reject(err)
          } else {
            resolve(data)
          }
        }
      )
    })
  }
}

module.exports = UploadService
